package chapter5.lessons.udpDemo03;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * @Project ：learn_java
 * @File ：ReceiveMessageDemo01.java
 * @IDE ：IntelliJ IDEA
 * @Author ：自由如风间
 * @Date ：2025/3/12 22:31
 * @Description ：For study.
 */

public class ReceiveMessageDemo01 {
    public static void main(String[] args) throws IOException {

        MulticastSocket ms = new MulticastSocket(10000);

        // 将当前本地添加到224.0.0.1的一组中
        InetAddress address = InetAddress.getByName("224.0.0.1");
        ms.joinGroup(address);

        byte[] bytes = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);

        ms.receive(dp);

        byte[] data = dp.getData();
        int len = dp.getLength();
        String ip = dp.getAddress().getHostAddress();
        String name = dp.getAddress().getHostName();

        System.out.println("ip为：" + ip + "主机为：" + name + "的人，发送了数据："
                           + new String(data, 0, len));

        ms.close();
    }
}
